<template>
  <div style="padding:30px;">
    <el-alert
        title="车次查询"
        type="info"
        :closable="false"
        show-icon
        description="user查询,admin可编辑"
        effect="dark"/>
    <div class="app-container">
    <el-input v-model="listQuery.train_number" placeholder="搜索车次" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
    <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <!-- 添加按钮 -->
      <el-button v-has="'add'" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    <el-table
      v-loading="listLoading"
      :data="list2"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="编号" >
        <template slot-scope="scope">
          {{ scope.row.train_no}}
        </template>
      </el-table-column>
      <el-table-column label="车次"  align="center">
        <template slot-scope="scope">
          {{ scope.row.train_number }}
        </template>
      </el-table-column>

      <el-table-column label="起始站"  align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.start_station }}</span>
        </template>
      </el-table-column>

      <el-table-column label="终点站"  align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.end_station }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="发车时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.start_time }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="到站时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.end_time }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="发车日期" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.arrive_day }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="handleHas()" label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)" >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total"  :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getplist" />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
         <!-- 姓名 -->
         <el-form-item label="编号" prop="train_no">
          <el-input v-model="temp.train_no" :disabled="dialogStatus=='update'" />
        </el-form-item>
          <el-form-item label="车次" prop="train_number" >
          <el-input v-model="temp.train_number" :disabled="dialogStatus=='update'" />
        </el-form-item> <!-- 姓名 -->
        <el-form-item label="发车日期" prop="arrive_day">
          <el-date-picker
          v-model="temp.arrive_day"
          type="date"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          placeholder="选择日期"
          :disabled="dialogStatus=='update'">
        </el-date-picker>
        </el-form-item>
        <el-form-item label="车厢数目" prop="train_carriage">
          <el-input v-model="temp.train_carriage" />
        </el-form-item>
        <el-form-item label="始发车站" prop="start_station">
          <el-input v-model="temp.start_station" />
        </el-form-item>
        <el-form-item label="发车时间" prop="start_time">
          <el-time-picker
            v-model="temp.start_time"
            value-format="hh:mm:ss"
            :picker-options="{
            start: '00:00:00',
            step: '00:00:01',
            end: '23:59:59'}"
            placeholder="开始时间">
      </el-time-picker>
        </el-form-item>
        <el-form-item label="终点站" prop="end_station">
          <el-input v-model="temp.end_station" />
        </el-form-item>
        <el-form-item label="终点时间" prop="end_time">
          <el-time-picker
          placeholder="结束时间"
          v-model="temp.end_time"
          value-format="hh:mm:ss"
          :picker-options="{
            start: '00:00:00',
            step: '00:00:01',
            end: '23:59:59',
            minTime: temp.start_time
    }"></el-time-picker>
        </el-form-item>
        <!-- 类型 -->
      </el-form>
      <!-- 页脚 -->
      <div slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <!-- 确定 -->
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import { getAllList,getList,addTrain,deleteTrain,editTrain } from '@/api/train'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import hasDirective from "@/directives/has";

export default {
  name:'Train',
  components: { Pagination },
  directives: {
    has: hasDirective,
  },
  data() {
    return {
      rowid:0,
      oldcard:'',//记录旧值
      dialogStatus:'',//对话框的状态，是添加，还是编辑
      dialogFormVisible: false,//对话框是否可见，初始不可见
      rules: {
        kind: [{ required: true, message: 'kind is required', trigger: 'change' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      temp: {
        train_no:'',
        train_number:'',
        train_carriage:0,
        arrive_day:'',
        start_station:'',
        start_time:'',
        end_station:'',
        end_station:''
      },
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      list: null,
      list2:null,
      listLoading: true,
      total:0,
      listQuery: {
        page: 1,
        limit: 5,
        train_number:undefined
      },
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }]
        },
    }
  },
  created() {
    this.fetchData()
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  methods: {
    handleHas(){
      if(JSON.parse(localStorage.getItem('permissions')).includes('editAndDelete')){
        return 1
      }
      else{
        return 0
      }
    },
  resetTemp() {
      this.temp = {
        train_no:'',
        train_number:'',
        train_carriage:0,
        arrive_day:'',
        start_station:'',
        start_time:'',
        end_station:'',
        end_station:''
      }
    },
  handleFilter() {
    this.listLoading = true
    console.log(this.listQuery.train_number)
    if (this.listQuery.train_number==undefined || this.listQuery.train_number=='')
      {this.fetchData()
    }
    else{
    getList({train_number:this.listQuery.train_number}).then(response =>{
      this.list=response.data.data
      this.total = this.list.length
      this.list2=this.list.slice(0,this.listQuery.limit);
      this.listLoading = false
    }) }  
  },
  fetchData() {
    this.listLoading = true
    getAllList().then(response => {
      this.list = response.data.data
      this.total = this.list.length
      this.list2=this.list.slice(0,this.listQuery.limit);
      this.listLoading = false
    })
  },
  getplist(){
    this.listLoading=true; 
    this.list2=this.list.slice((this.listQuery.page-1)*this.listQuery.limit,(this.listQuery.page)*this.listQuery.limit)
    this.listLoading=false;
  },
  handleCreate() {
  // 重设默认值
  this.resetTemp()
  // 设置模态框操作状态为新增
  this.dialogStatus = 'create'
  // 设置模态框可见
  this.dialogFormVisible = true
  // $nextTick：在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。
  // 使用nextTick可立即使用更完的DOM
  this.$nextTick(() => {
    // 移除表单校验结果
    this.$refs['dataForm'].clearValidate()
    // 移除校验结果并重置字段值 (未测试)
    // this.$refs['dataForm'].resetFields()
  })
},
  handleDelete(row, index) {
    this.$confirm('此操作将删除该车次的信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$notify({
      title: '成功',
      message: '删除成功',
      type: 'success',
      duration: 2000
    })
    // 删除数组中指定元素
    this.list2.splice(index, 1)
    this.total=this.total-1
    deleteTrain({train_no:row.train_no,train_number:row.train_number,arrive_day:row.arrive_day})
      }).catch(() => {
        this.$notify.info({
      title: '取消',
      message: '取消删除',
      duration: 2000
    })      
      });
  },
  createData() {
    this.$refs['dataForm'].validate((valid) => {
      
      if (valid) {
        // 新增接口
        addTrain(this.temp).then((response) => {
          // 追加新增数据
          this.list2.unshift(this.temp)
          this.total=this.total+1
          // 模态框不可见
          this.dialogFormVisible = false
          // 提示信息
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            // 持续时间
            duration: 2000
          })
        })
      }
    })
  },
  handleUpdate(row,index) {
    this.rowid=index
    this.temp = Object.assign({}, row) // copy obj
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
    })
  },
  updateData() {
    this.$refs['dataForm'].validate((valid) => {
      if (valid) {
        const tempData = Object.assign({}, this.temp)
        editTrain(tempData).then(() => {
          const index = this.rowid
          this.list2.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }
    })
  },
  }
}
</script>
